<template>
    <el-button plain type="primary" style="margin-bottom: 10px;" @click="Open()">添加</el-button>
    <el-button plain type="primary" style="float: right;" @click="exportOrder">导出</el-button>
    <el-button @click="batchDelete" type="danger" style="float: left; margin-right: 10px;">批量删除</el-button>
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column fixed type="index" label="序号" width="60" />
        <el-table-column prop="produceCode" label="生产工单编号" width="150" />
        <el-table-column prop="produceName" label="生产工单名称" width="150" />
        <el-table-column prop="produceType" label="生产状态" width="150">
            <template v-slot="scope">
                <el-tag type="parmary" v-if="scope.row.finishProduceNum == 0">待发布</el-tag>
                <el-tag type="danger"
                    v-if="scope.row.finishProduceNum >= 1 && scope.row.finishProduceNum < scope.row.produceNum">进行中</el-tag>
                <el-tag type="success" v-if="scope.row.finishProduceNum == scope.row.produceNum">已完成</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="orderGoods" label="下单产品" width="130" />
        <el-table-column prop="clientName" label="客户" width="180" />
        <el-table-column prop="materialGroupName" label="物料群组" width="180" />
        <el-table-column prop="warehouseAddr" label="仓库地址" width="180" />
        <el-table-column prop="flowName" label="所属工艺" width="180" />
        <el-table-column prop="workShopName" label="所属车间" width="180" />
        <el-table-column prop="productionLineName" label="所属产线" width="180" />
        <el-table-column prop="startDate" label="起始时间" width="180">
            <template #default="scope">
                {{ moment(scope.row.startDate).format('YYYY-MM-DD') }}
            </template>
        </el-table-column>
        <el-table-column prop="entDate" label="结束时间" width="180">
            <template #default="scope">
                {{ moment(scope.row.entDate).format('YYYY-MM-DD') }}
            </template>
        </el-table-column>
        <el-table-column prop="produceNum" label="生产数量" width="180" />
        <el-table-column prop="finishProduceNum" label="已生产数量" width="180" />
        <el-table-column label="生产完整度" width="180">
            <template #default="scope">
                <div class="progress-container">
                    <div class="progress-bar" :style="{
                        width: scope.row.produceNum > 0 ?
                            Math.round((scope.row.finishProduceNum / scope.row.produceNum) * 100) + '%' : '0%'
                    }">
                        {{ scope.row.produceNum > 0 ?
                            Math.round((scope.row.finishProduceNum / scope.row.produceNum) * 100) + '%' : '0%' }}
                    </div>
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="createrPeople" label="创建人" width="130" />
        <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="scope">
                {{ moment(scope.row.createTime).format('YYYY-MM-DD') }}
            </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="180">
            <template #default="scope">
                {{ moment(scope.row.updateTime).format('YYYY-MM-DD') }}
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120">
            <template v-slot="scope">
                <el-button link type="warning" :disabled="scope.row.produceNum == scope.row.finishProduceNum"
                    @click="OpenUpdate(scope.row)">编辑</el-button>
                <el-button link type="danger" @click="Del(scope.row)">删除</el-button>
                <el-button link type="primary" @click="Get(scope.row.id)">详情</el-button>
                <!-- 领料申请按钮 - 工单完成时禁用 -->
                <el-button 
                  link 
                  type="success" 
                  @click="ToMaterialAsk(scope.row)" 
                  :disabled="scope.row.finishProduceNum == scope.row.produceNum"
                  :title="scope.row.finishProduceNum == scope.row.produceNum ? '工单已完成，无法申请领料' : '申请领料'"
                >
                  领料申请
                </el-button>
                <!-- <el-button v-if="scope.row.finishProduceNum == scope.row.produceNum" link type="warning" @click="ToQuality(scope.row)">质检</el-button> -->
                <!-- 质检按钮部分修改 -->
                <el-button v-if="scope.row.finishProduceNum == scope.row.produceNum" link
                    :type="scope.row.isInspected ? 'default' : 'warning'" :disabled="scope.row.isInspected"
                    @click="ToQuality(scope.row)">
                    {{ scope.row.isInspected ? '已质检' : '质检' }}
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 添加生产工单 -->
    <el-dialog v-model="dialogVisible" title="添加生产工单" width="700px" class="work-order-dialog" destroy-on-close>
        <div class="work-order-header">
            <div class="work-order-title">
                <el-icon class="work-order-icon"><Document /></el-icon>
                <span>新建生产工单</span>
            </div>
            <div class="work-order-code">
                工单编号：系统自动生成
            </div>
        </div>

        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="work-order-form">
            <div class="work-order-section">
                <div class="section-title">基本信息</div>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="工单名称" prop="produceName">
                            <el-input v-model="ruleForm.produceName" placeholder="请输入生产工单名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户" prop="clientId">
                            <el-select v-model="ruleForm.clientId" placeholder="请选择客户">
                                <el-option v-for="item in ClientData" :label="item.clientName" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="下单产品" prop="orderId">
                            <el-select v-model="ruleForm.orderId" placeholder="请选择下单物品">
                                <el-option v-for="item in OrderData" :label="item.orderGoods" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="物料群组" prop="materialGroupId">
                            <el-select v-model="ruleForm.materialGroupId" placeholder="请选择物料群组">
                                <el-option v-for="item in GrouptableData" :label="item.materialGroupName" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <div class="work-order-section">
                <div class="section-title">生产信息</div>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="仓库地址" prop="warehouseId">
                            <el-select v-model="ruleForm.warehouseId" placeholder="请选择仓库地址">
                                <el-option v-for="item in WareData" :label="item.warehouseName" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="所属工艺" prop="processFlowId">
                            <el-select v-model="ruleForm.processFlowId" placeholder="请选择工艺">
                                <el-option v-for="item in FlowData" :label="item.flowName" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="所属车间" prop="workShopId">
                            <el-select v-model="ruleForm.workShopId" placeholder="请选车间">
                                <el-option v-for="item in WorkData" :label="item.workShopName" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="所属产线" prop="productionLineId">
                            <el-select v-model="ruleForm.productionLineId" placeholder="请选择产线">
                                <el-option v-for="item in LineData" :label="item.productionLineName" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>

            <div class="work-order-section">
                <div class="section-title">计划信息</div>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="起始时间" prop="startDate">
                            <el-date-picker
                                v-model="ruleForm.startDate"
                                type="date"
                                placeholder="请选择起始时间"
                                style="width: 100%"
                                format="YYYY-MM-DD"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结束时间" prop="entDate">
                            <el-date-picker
                                v-model="ruleForm.entDate"
                                type="date"
                                placeholder="请选择结束时间"
                                style="width: 100%"
                                format="YYYY-MM-DD"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="生产数量" prop="produceNum">
                            <el-input-number 
                                v-model="ruleForm.produceNum" 
                                :min="1" 
                                controls-position="right"
                                style="width: 100%"
                                placeholder="请输入生产数量" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
        </el-form>

        <template #footer>
            <div class="work-order-footer">
                <el-button @click="dialogVisible = false" plain>取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    <el-icon><Check /></el-icon>
                    提交工单
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 修改订单 -->
    <el-dialog v-model="dialogVisibleUpdate" title="编辑" width="500px">

        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">

            <!-- <el-form-item label="生产工单名称" prop="produceName">
                <el-input v-model="ruleForm.produceName" placeholder="请输入库区数量" />
            </el-form-item>

            <el-form-item label="客户" prop="clientId">
                <el-select v-model="ruleForm.clientId" placeholder="请选择客户">
                    <el-option v-for="item in ClientData" :label="item.clientName" :value="item.id" />
                </el-select>

            </el-form-item>
            <el-form-item label="下单产品" prop="orderId">
                <el-select v-model="ruleForm.orderId" placeholder="请选择下单物品">
                    <el-option v-for="item in OrderData" :label="item.orderGoods" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="物料群组" prop="materialGroupId">
                <el-select v-model="ruleForm.materialGroupId" placeholder="请选择物料群组">
                    <el-option v-for="item in GrouptableData" :label="item.materialGroupName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="仓库地址" prop="warehouseId">
                <el-select v-model="ruleForm.warehouseId" placeholder="请选择仓库地址">
                    <el-option v-for="item in WareData" :label="item.warehouseName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="所属工艺" prop="processFlowId">
                <el-select v-model="ruleForm.processFlowId" placeholder="请选择工艺">
                    <el-option v-for="item in FlowData" :label="item.flowName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="所属车间" prop="orderId">
                <el-select v-model="ruleForm.workShopId" placeholder="请选车间">
                    <el-option v-for="item in WorkData" :label="item.workShopName" :value="item.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="所属产线" prop="productionLineId">
                <el-select v-model="ruleForm.productionLineId" placeholder="请选择产线">
                    <el-option v-for="item in LineData" :label="item.productionLineCode" :value="item.id" />
                </el-select>
            </el-form-item> -->

            <el-form-item label="起始时间" prop="startDate">
                <el-input type="date" v-model="ruleForm.startDate" placeholder="" />
            </el-form-item>
            <el-form-item label="结束时间" prop="entDate">
                <el-input type="date" v-model="ruleForm.entDate" placeholder="" />
            </el-form-item>
            <!-- <el-form-item label="生产数量" prop="produceNum">
                <el-input type="number" v-model="ruleForm.produceNum" placeholder="" />
            </el-form-item> -->
             <el-form-item label="已生产数量" prop="produceNum">
                <el-input type="number" v-model="ruleForm.finishProduceNum" placeholder="请输入已生产数量" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisibleUpdate = false">取消</el-button>
                <el-button type="primary" @click="updateProductionOrder">修改</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 质检弹窗 -->
    <el-dialog v-model="qualityDialogVisible" title="质检记录" width="500px">
        <el-form ref="qualityFormRef" :model="qualityForm" :rules="rulesQuality" label-width="120px">
            <el-form-item label="生产编号">
                <el-input v-model="productionInfo.produceCode" disabled />
            </el-form-item>
            <el-form-item label="生产订单名称">
                <el-input v-model="productionInfo.produceName" disabled />
            </el-form-item>
            <el-form-item label="物料群组" prop="materialGroupId">
                <el-select v-model="qualityForm.materialGroupId" placeholder="请选择物料群组" disabled>
                    <el-option v-for="item in GrouptableData" :key="item.id" :label="item.materialGroupName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="检验数量" prop="inspectedQuantity">
                <el-input v-model.number="qualityForm.inspectedQuantity" disabled />
            </el-form-item>
            <el-form-item label="合格数量" prop="qualifiedQuantity">
                <el-input v-model.number="qualityForm.qualifiedQuantity" placeholder="请输入合格数量" />
                <div class="el-form-item__help">
                    提示：合格数量必须在0到{{ qualityForm.inspectedQuantity }}之间
                </div>
            </el-form-item>
            <el-form-item label="质检人员" prop="inspector">
                <el-input v-model="qualityForm.inspector" placeholder="请输入质检人员" />
            </el-form-item>
            <el-form-item label="创建人" prop="createrPeople">
                <el-input v-model="qualityForm.createrPeople" disabled />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="qualityDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitQualityForm">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <!--分页-->
    <el-pagination v-model:current-page="page.Index" v-model:page-size="page.Size" :page-sizes="[5, 10, 20, 30]"
        :background="true" layout="total, sizes, prev, pager, next, jumper" :total="page.totalcount" />
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from 'vue';
import axios from 'axios';

import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
import { useRouter } from 'vue-router';
import { Watch, Document, Check } from '@element-plus/icons-vue';
const router = useRouter()
const pinia = useCounterStore();
const tableData = ref([])

// 导出订单
const exportOrder = () => {
    axios.get('/api/ProductionModules/ExportOrder', {
        responseType: 'blob' // 重要：告诉 axios 返回二进制流
    })
        .then(response => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', '订单信息.xlsx'); // 可自定义文件名
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        })
        .catch(error => {
            ElMessage.error('导出失败，请重试');
            console.error('Export error:', error);
        });
};
//批量删除功能
const selectedRows = ref<number[]>([]);
const handleSelectionChange = (val: any[]) => {
    selectedRows.value = val.map(item => item.id);
}
//调用后端批量删除接口
const batchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的记录');
        return;
    }
    ElMessageBox.confirm('确定要删除选中的记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        axios.delete('/api/ProductionModules/BatchDelProductions', { params: { IdString: selectedRows.value.toString() } }).then(res => {
            if (res.data.code == 200) {
                ElMessage.success('删除成功');
                GetProducetion();
            } else {
                ElMessage.error(res.data.message);
            }
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

//产线向后端传参
const page = reactive({
    Index: 1,
    Size: 5,
    totalcount: 0
})
//车间向后端传参

//钩子
onMounted(() => {

    GetProducetion()
    GetGroup()
    GetLine()
    GetClient()
    GetProcessFlow()
    getWare()
    getOrder()
    getWork()
})
const Get = (Id: any) => {
    router.push({
        path: "/Get",
        query: {
            Id: Id
        }
    })
}

//生产工单显示
const GetProducetion = () => {
    axios.get('/api/ProductionModules/GetProducetion', { params: page }).then(res => {
        if (res.data.code == 200) {
            tableData.value = res.data.totalPage
            page.totalcount = res.data.totalcount
        }
    })
}


//#region 工序查询 物料群组 

const GrouptableData: any = ref([])
const GetGroup = () => {
    axios.get('/api/Pulldown/GetGroup').then(res => {
        if (res.data.code == 200) {
            GrouptableData.value = res.data.data
        }
    })
}
const LineData: any = ref([])
const GetLine = () => {
    axios.get('/api/Pulldown/GetLine').then(res => {
        if (res.data.code == 200) {
            LineData.value = res.data.data
        }
    })
}
const FlowData: any = ref([])
const GetProcessFlow = () => {
    axios.get('/api/Pulldown/GetProcessFlow').then(res => {
        if (res.data.code == 200) {
            FlowData.value = res.data.data
        }
    })
}
const ClientData: any = ref([])
const GetClient = () => {
    axios.get('/api/Pulldown/GetClient').then(res => {
        if (res.data.code == 200) {
            ClientData.value = res.data.data
        }
    })
}
const OrderData: any = ref([])
const getOrder = () => {
    axios.get('/api/Pulldown/getOrder').then(res => {
        if (res.data.code == 200) {
            OrderData.value = res.data.data
        }
    })
}
const WareData: any = ref([])
const getWare = () => {
    axios.get('/api/Pulldown/getWare').then(res => {
        if (res.data.code == 200) {
            WareData.value = res.data.data
        }
    })
}
const WorkData: any = ref([])
const getWork = () => {
    axios.get('/api/Pulldown/getWork').then(res => {
        if (res.data.code == 200) {
            WorkData.value = res.data.data
        }
    })
}
//#endregion


// 控制弹窗显示
const dialogVisible = ref(false);
const Open = () => {
    dialogVisible.value = true;
    clearUpdateForm();
}



const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    "produceCode": "",
    "produceName": "",
    "produceType": 0,
    "clientId": "",
    "orderId": "",
    "materialGroupId": "",
    "warehouseId": "",
    "processFlowId": "",
    "workShopId": "",
    "productionLineId": "",
    "startDate": "",
    "entDate": "",
    "produceNum": "",
    "finishProduceNum": 0,
    "ischeck": false,
    "createrPeople": "admin",
    
})

watch(page,()=>{
GetProducetion();
})

const rules = reactive<FormRules>({
    productionLineCode: [
        { required: true, message: '请输入产线编码', trigger: 'blur' },
    ],
    productionLineName: [
        {
            required: true,
            message: '请输入产线名称',
            trigger: 'blur',
        },
    ],
    workShopId: [
        {
            required: true,
            message: '请选择车间',
            trigger: 'blur',
        }],
    productionLineDesc: [
        {
            required: true,
            message: '请输入产线描述',
            trigger: 'blur',
        },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.post('/api/ProductionModules/AddPro', ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    console.log(ruleForm)
                    dialogVisible.value = false;
                    GetProducetion(); // 提交成功后刷新表格数据
                } else {
                    ElMessage.error(res.data.message)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}




//#region 修改


const dialogVisibleUpdate = ref(false);
const OpenUpdate = (row: any) => {
    dialogVisibleUpdate.value = true
    Object.assign(ruleForm, row)
    ruleForm.startDate = row.startDate.split('T')[0];
    ruleForm.entDate = row.entDate.split('T')[0];
}
//清空修改表单数据源
const clearUpdateForm = () => {
    ruleForm.produceCode = "";
    ruleForm.produceName = "";
    ruleForm.produceType = 0;
    ruleForm.clientId = "";
    ruleForm.orderId = "";
    ruleForm.materialGroupId = "";
    ruleForm.warehouseId = "";
    ruleForm.processFlowId = "";
    ruleForm.workShopId = "";
    ruleForm.productionLineId = "";
    ruleForm.startDate = "";
    ruleForm.entDate = "";
    ruleForm.produceNum = "";
    ruleForm.finishProduceNum = 0;
    ruleForm.ischeck = false;
    ruleForm.createrPeople = '';
    
}
const updateProductionOrder = () => {
    axios.put("/api/ProductionModules/ProduceUpdate", ruleForm).then(res => {
        if (res.data.code == 200) {
            ElMessage.success(res.data.message);
            dialogVisibleUpdate.value = false;
            GetProducetion(); // 提交成功后刷新表格数据
        } else {
            ElMessage.error(res.data.message)
        }
    })

}




const ruleFormUpdate = reactive({
    "id": null,
    "productionLineCode": "",
    "productionLineName": "",
    "workShopId": null,
    "productionLineDesc": "",
    "updaterPeople": pinia.piniaDto.accountName
})

//#endregion


//删除
const Del = (row: any) => {
    ElMessageBox.confirm(
        '确定要删除该仓库吗？删除后数据将无法恢复。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {

            axios({
                url: "/api/ProductionModules/DeletePro",
                method: 'post',
                data: row
            })
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.message);
                        GetProducetion(); // 删除成功后刷新表格数据
                    } else {
                        ElMessage.error(res.data.message);
                    }
                }).catch(error => {
                    ElMessage.error('删除失败，请重试');
                    console.error('Delete error:', error);
                });
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
}


// const ToQuality = (row: any) => {
//   // 通过路由参数传递生产编号
//   router.push({
//     path: "/QualityInspections",
//     query: {
//       produceCode: row.produceCode
//     }
//   });
// };


//#region  质检
// 质检弹窗控制
const qualityDialogVisible = ref(false);
const qualityFormRef = ref<FormInstance>();
// 新增：记录当前正在质检的行数据
const currentQualityRow = ref<any>(null);

// 质检表单数据（适配新API字段）
const qualityForm = reactive({
    productionOrderId: 0,       // 生产工单ID
    materialGroupId: 0,         // 物料群组ID（新API必填）
    inspectedQuantity: 0,       // 检验数量（新API必填）
    qualifiedQuantity: 0,       // 合格数量
    inspector: '',              // 质检人员
    createrPeople: pinia.piniaDto.accountName  // 创建人（从pinia获取当前用户）
});

// 生产订单基础信息（用于展示不可修改的字段）
const productionInfo = reactive({
    produceCode: '',            // 生产编号
    produceName: '',            // 生产订单名称
    materialGroupName: ''       // 物料群组名称
});

// 质检表单验证规则（新增物料群组验证）
const rulesQuality = reactive<FormRules>({
    materialGroupId: [
        { required: true, message: '物料群组不能为空', trigger: 'change' }
    ],
    inspectedQuantity: [
        { required: true, message: '检验数量不能为空', trigger: 'blur' }
    ],
    qualifiedQuantity: [
        { required: true, message: '请输入合格数量', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value < 0 || value > qualityForm.inspectedQuantity) {
                    callback(new Error(`合格数量必须在0到${qualityForm.inspectedQuantity}之间`));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    inspector: [
        { required: true, message: '请输入质检人员', trigger: 'blur' }
    ]
});

// 质检弹窗显示（回填数据）
const ToQuality = (row: any) => {
    // 记录当前操作的行数据
    currentQualityRow.value = row;

    // 回填生产订单基础信息（用于展示）
    productionInfo.produceCode = row.produceCode;
    productionInfo.produceName = row.produceName;
    productionInfo.materialGroupName = row.materialGroupName;

    // 回填表单提交数据（适配新API）
    qualityForm.productionOrderId = row.id;
    qualityForm.materialGroupId = row.materialGroupId;  // 物料群组ID
    qualityForm.inspectedQuantity = row.produceNum;     // 检验数量=产品数量
    qualityForm.qualifiedQuantity = 0;                  // 重置合格数量
    qualityForm.inspector = '';                         // 重置质检人员

    // 显示弹窗
    qualityDialogVisible.value = true;
};

// 提交质检表单（适配新API）
const submitQualityForm = async () => {
    if (!qualityFormRef.value) return;

    await qualityFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 调用新API
                const response = await axios.post(
                    '/api/QualityInspection/QualityInspectionCreate',
                    qualityForm  // 直接传递整个表单对象（已包含所有必填字段）
                );

                if (response.data.code === 200) {
                    ElMessage.success('质检记录创建成功');

                    //   // 更新当前行的质检状态
                    //   if (currentQualityRow.value) {
                    //     // 找到当前行在表格数据中的位置并更新状态
                    //     const rowIndex = tableData.value.findIndex(
                    //       item => item.id === currentQualityRow.value.id
                    //     );
                    //     if (rowIndex !== -1) {
                    //       tableData.value[rowIndex].isInspected = true;
                    //     }
                    //   }

                    qualityDialogVisible.value = false;
                    // 注释掉路由跳转，避免页面离开
                    // router.push({ path: '/QualityInspections' });
                } else {
                    ElMessage.error(response.data.message || '创建质检记录失败');
                }
            } catch (error) {
                ElMessage.error('网络异常，创建质检记录失败');
                console.error('Create quality inspection error:', error);
            }
        }
    });
};

// 跳转到物料申请单页面
const ToMaterialAsk = (row: any) => {
    // 跳转到物料申请单页面，并传递生产工单名称
    router.push({
        path: "/MaterialAsk",
        query: {
            produceName: row.produceName,  // 传递生产工单名称
            produceCode: row.produceCode   // 传递生产工单编号
        }
    });
};

//#endregion
</script>

<style scoped>
/* 工单对话框样式 */
.work-order-dialog :deep(.el-dialog__header) {
    padding: 15px 20px;
    margin: 0;
    background-color: #f0f7ff;
    border-bottom: 1px solid #e6f0fc;
    border-radius: 8px 8px 0 0;
}

.work-order-dialog :deep(.el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    color: #1677ff;
}

.work-order-dialog :deep(.el-dialog__body) {
    padding: 0;
}

.work-order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    background-color: #f5faff;
    border-bottom: 1px dashed #d9e8ff;
}

.work-order-title {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #1677ff;
}

.work-order-icon {
    margin-right: 8px;
    font-size: 20px;
    color: #1677ff;
}

.work-order-code {
    font-size: 14px;
    color: #666;
    background-color: #f0f7ff;
    padding: 4px 12px;
    border-radius: 4px;
    border: 1px solid #d9e8ff;
}

.work-order-form {
    padding: 20px 24px;
}

.work-order-section {
    margin-bottom: 24px;
    padding: 16px;
    background-color: #fafafa;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
}

.work-order-section:last-child {
    margin-bottom: 0;
}

.section-title {
    margin-bottom: 16px;
    padding-bottom: 8px;
    font-size: 15px;
    font-weight: 600;
    color: #333;
    border-bottom: 1px solid #eee;
    position: relative;
}

.section-title::before {
    content: "";
    position: absolute;
    left: 0;
    bottom: -1px;
    width: 40px;
    height: 2px;
    background-color: #1677ff;
}

.work-order-footer {
    display: flex;
    justify-content: flex-end;
    padding: 10px 20px;
    background-color: #f9f9f9;
    border-top: 1px solid #eee;
    border-radius: 0 0 8px 8px;
}

.work-order-dialog :deep(.el-form-item__label) {
    font-weight: 500;
    color: #333;
}

.work-order-dialog :deep(.el-input__wrapper),
.work-order-dialog :deep(.el-select .el-input__wrapper),
.work-order-dialog :deep(.el-input-number .el-input__wrapper) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.work-order-dialog :deep(.el-input__wrapper:hover),
.work-order-dialog :deep(.el-select .el-input__wrapper:hover),
.work-order-dialog :deep(.el-input-number .el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #c0c4cc inset;
}

.work-order-dialog :deep(.el-input__wrapper.is-focus),
.work-order-dialog :deep(.el-select .el-input__wrapper.is-focus),
.work-order-dialog :deep(.el-input-number .el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #1677ff inset;
}

.work-order-dialog :deep(.el-button--primary) {
    background-color: #1677ff;
    border-color: #1677ff;
}

.work-order-dialog :deep(.el-button--primary:hover) {
    background-color: #4096ff;
    border-color: #4096ff;
}

/* 原有分页样式 */
.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 10px;
    background-color: #f9fafb;
    border-radius: 8px;
}

.custom-pagination {
    --el-pagination-item-size: 32px;
    --el-pagination-item-bg: #ffffff;
    --el-pagination-item-color: #606266;
    --el-pagination-item-hover-color: #4096ff;
    --el-pagination-item-active-color: #ffffff;
    --el-pagination-item-active-bg: #4096ff;
    --el-pagination-border-radius: 6px;
    --el-pagination-margin: 0 5px;
}

.custom-pagination .el-pagination__prev,
.custom-pagination .el-pagination__next {
    width: 32px;
    height: 32px;
    border-radius: 6px;
}

.custom-pagination .el-pagination__sizes {
    margin-right: 10px;
}

.custom-pagination .el-pagination__total {
    margin-right: 10px;
    color: #606266;
}

.custom-pagination .el-pagination__item {
    margin: 0 5px;
    border-radius: 6px;
    min-width: 32px;
    height: 32px;
    line-height: 32px;
}

.custom-pagination .el-pagination__item:hover {
    background-color: #f0f5ff;
}

.custom-pagination .el-pagination__item.is-active {
    background-color: #4096ff;
    color: #ffffff;
}

.progress-container {
    width: 100%;
    background-color: #f0f0f0;
    border-radius: 3px;
    overflow: hidden;
    height: 24px;
    border: 1px solid #dcdfe6;
}

.progress-bar {
    height: 100%;
    background-color: #1DD1A1;
    color: #fff;
    text-align: center;
    line-height: 24px;
    font-size: 12px;
    font-weight: bold;
    min-width: 30px;
}
</style>